/*
 * DownloadTestPanel.cpp
 *
 *  Created on: 2012-11-3
 *      Author: tutu
 */

#include "DownloadTestPanel.h"
#include "../TContext.h"
#include <QMessageBox>
#include <QFileDialog>

DownloadTestPanel::DownloadTestPanel(QWidget *parent) : QWidget(parent)
{
	_idEdit = new QLineEdit(this);
	_idEdit->setText("Id");
	_idEdit->setGeometry(10, 10, 150, 30);

	_saveButton = new QPushButton(this);
	_saveButton->setText("Save");
	_saveButton->setGeometry(10, 50, 100, 30);
	connect(_saveButton, SIGNAL(clicked()), this, SLOT(saveButtonClicked()));

	_saveAsButton = new QPushButton(this);
	_saveAsButton->setText("Save As");
	_saveAsButton->setGeometry(10, 90, 100, 30);
	connect(_saveAsButton, SIGNAL(clicked()), this, SLOT(saveAsButtonClicked()));

	_requester = TContext::instance()->requesterFactory()->createDownloadRequester();
	connect(_requester.data(), SIGNAL(downloadFinished(bool, QString)), this, SLOT(downloadFinished(bool, QString)));
}

DownloadTestPanel::~DownloadTestPanel()
{
	// TODO Auto-generated destructor stub
}

void DownloadTestPanel::saveButtonClicked()
{
	if(_idEdit->text().isEmpty())
	{
		QMessageBox::warning(NULL, "Error", "No id");
		return;
	}
	_requester->download(_idEdit->text().toInt());
}

void DownloadTestPanel::saveAsButtonClicked()
{
	QString filename = QFileDialog::getOpenFileName(this, tr("Save File"),
													"C:/",
													tr("Files (*.*)"));
	_requester->download(_idEdit->text().toInt(), filename);
}

void DownloadTestPanel::downloadFinished(bool error, QString localFilename)
{
	if(!error)
	{
		QMessageBox::warning(NULL, "Result", "Download Success. File at "+localFilename);
	}
	else
	{
		QMessageBox::warning(NULL, "Result", "Download Failure.");
	}
}
